from BasicLibraries import *
import get_data as gd
import regression as rg
from matplotlib import rc

plt.rcParams['xtick.major.pad']='8'
rc('text', usetex=True)
rc('font', size=24)
rc('legend', fontsize=24)
rc('text.latex', preamble=r'\usepackage{cmbright}')
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
color = ['#e95057', '#0080c4', '#00a989', '#464646']


#%% Effect of diversification on EBITDA at risk
def estimate_effort_EAR(comp, db, IMR, esg, tc,  sdgs, earning_measure, dummies, YFE, sdgs_options_name, diversification_type, SI=False):
    '''
    The idea is that these strategies are not only implemented for reducting emissions
    but also for reducing risk exposure to transition risk
    '''
    print(sdgs_options_name, '-', diversification_type)
    res_bar = pd.DataFrame()
    
    #======
    dep_var = 'EAR'
    earning_type = earning_measure.copy()
    #======
    list_of_data = dict()
    for earning_scenario in ['low', 'medium', 'high']:
        for horizon_scenario in [2030,2040,2050]:
            print(earning_scenario, horizon_scenario)
            initiatives, missing_sdgs, initiatives_sdgs, initiatives_to_remove = gd.get_initiatives(sdgs)
            #==
            dt, dummies = gd.merge_with_behavioural_data(initiatives, initiatives_sdgs, missing_sdgs, sdgs,  \
                                                         initiatives_to_remove, comp, db, IMR, esg, tc, 
                                                         earning_type, \
                                                         diversification_measure = diversification_type,
                                                         impact_type= dep_var, 
                                                         scenario_type = earning_scenario, 
                                                         scenario_horizon = horizon_scenario, 
                                                         years_FE=YFE)
            dt_ws = dt.copy()
            dt_ws = dt_ws[dt_ws.total_effort > 1]
            dt_ws[dummies] = dt_ws[dummies].astype(int)
            dt[dummies] = dt[dummies].astype(int)
            #==
            res, resNUM, x = rg.make_EAR_regression(dt_ws, dummies,  emission_var = dep_var, years_FE=YFE)
            res.index = [sdgs_options_name]
            
            resNUM[3] = (resNUM[2]-resNUM[1])/2
            resNUM.columns = ['Effect', 'LB', 'UB', 'Uncertainty']
            resNUM.index = res.columns
            resNUM = resNUM.rename(index = {'Risk mitigation': 'Risk Mit.', 'Stakeholders engagement': 'Stak.Eng.'})
            resNUM['Emission type'] = [dep_var]*len(resNUM)
            resNUM['scenario'] = [earning_scenario]*len(resNUM)
            resNUM['horizon'] = [horizon_scenario]*len(resNUM)
            
            res_bar = pd.concat((res_bar, resNUM))
            list_of_data[earning_scenario+'_'+str(horizon_scenario)] = x
       
            res.loc['Assets\' characteristics'] = 'Yes'
            res.loc['Sector fixed effects']     = 'Yes'
            res.loc['Country fixed effects']    = 'Yes'
            res.loc['Year fixed effects']       = ['Yes' if YFE == True else 'No'][0]
            res.loc['Self-selectivity']         = 'Yes'
            print(res.to_latex())
    #===
    cols = ['#85af38', '#e57314', '#e30613']
    shifts = [-1,0,1]
    figs = 0
    
    fig, axs = plt.subplots(4, 1, sharex=True, figsize = (10,14))
    # Remove horizontal space between axes
    res_bar.rename(index = {'Diversification': 'Response diversity',
                            'Risk Mit.': 'Risk mitigation',
                            'Stak.Eng.': 'Stakeholders engagement'}, inplace = True)
    res_bar['scenario'] = res_bar['scenario'].apply(lambda x: x.capitalize())
    fig.text(-0.025, 0.5, 'Impact on earnings at risk', va='center', rotation='vertical')
    for d in res_bar.index.unique():
        get_maxs, get_mins = [], []
        fig.subplots_adjust(hspace=0.25)
        Z = res_bar.loc[d]
        Z = Z.set_index('horizon')
        count=0
        for m in Z['scenario'].unique():
            A = Z[Z['scenario'] == m]
            A.index +=shifts[count]
            A=  A.rename(columns = {'Effect': m})
            A[m].plot(marker = 'o', ms= 15, ls = '', c = cols[count], yerr = A.Uncertainty, capsize = 4, ax = axs[figs], title = d)
            count+=1
            get_mins.append(A['LB'].min() - abs(A['LB'].min()*0.1))
            get_maxs.append(A['UB'].min() + A['UB'].min()*0.5)
        axs[figs].axhline(y  = 0, ls = '-.', lw = 0.5, c = 'k')
        axs[figs].set_ylim(-0.10, 0.05)#np.min(get_mins),0.05)
        figs+=1
    plt.xlabel('Horizon year, H', labelpad = 10)
    plt.xticks([2030,2040,2050])
    axs[-1].set_xticklabels([2030,2040,2050])
    axs[0].legend(loc = 'center left', bbox_to_anchor = (1,0.5), title = 'Scenario')
    if SI:
        plt.savefig('Figures/Figure6_SI.pdf', dpi = 100, bbox_inches = 'tight')
    else:
        plt.savefig('Figures/Figure6.pdf', dpi = 100, bbox_inches = 'tight')

    return res_bar, list_of_data



